<template>
    <div class="common-layout">
        <el-container>
            <el-header>
                <el-menu class="el-menu-demo" mode="horizontal" background-color="#545c64" text-color="#fff"
                    active-text-color="#ffd04b">
                    <el-menu-item index="1">
                        <h5 @click="toUserMenu">员工系统</h5>
                    </el-menu-item>
                    <el-menu-item index="2">
                        <el-badge :value="msgNumStoreData" :min="1" :max="99">
                            <el-icon @click="toUserMessage">
                                <ChatDotRound />
                            </el-icon>
                        </el-badge>
                    </el-menu-item>
                    <el-sub-menu index="3">
                        <template #title>
                            <el-icon>
                                <Setting />
                            </el-icon>
                        </template>
                        <el-menu-item index="3-1" @click="modifyDialogVisible = true">
                            修改密码
                        </el-menu-item>
                        <el-menu-item index="3-2" @click="exit">
                            退出登录
                        </el-menu-item>
                    </el-sub-menu>
                    <el-menu-item index="4" style="margin-left: 65%;">
                        <div>
                            <el-avatar @click="avatarDialogVisible = true" :src="src" />
                        </div>
                    </el-menu-item>
                    <el-menu-item index="5">
                        <h5>{{ name }}</h5>
                    </el-menu-item>
                </el-menu>
            </el-header>
            <el-main>
                <RouterView></RouterView>
            </el-main>
        </el-container>
        <!-- 头像展示对话框 -->
        <el-dialog v-model="avatarDialogVisible" style="width: 20%;" title="头像" draggable center>
            <el-form style="margin-left: 50px;" center>
                <el-form-item>
                    <el-image style="width: 100px; height: 100px;margin-left: 30px;" :src="src" :fit="fits" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" style="margin-top: 10px;margin-left: 40px;"
                        @click="modifyAvatarDialogVisible = true">更换头像</el-button>
                </el-form-item>
            </el-form>
            <!-- 更换头像对话框 -->
            <el-dialog v-model="modifyAvatarDialogVisible" style="width: 20%;" title="更换头像" draggable center>
                <el-upload class="avatar-uploader" style="margin-left: 60px;" :action="modifyEmpImage"
                    :show-file-list="false" :headers="getTokenHeaders" :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload">
                    <img v-if="src" :src="src" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
                <el-button type="primary" style="margin-top: 10px;margin-left: 100px"
                    @click="modifyAvatarDialogVisible = false">确定</el-button>
            </el-dialog>
        </el-dialog>
    </div>
    <!-- 修改密码对话框 -->
    <el-dialog v-model="modifyDialogVisible" title="修改密码" width="500" draggable>
        <el-form ref="ruleFormRef" style="max-width: 400px" :model="ruleForm" :rules="modifyRules" label-width="auto"
            class="demo-ruleForm" :size="formSize" status-icon>
            <el-form-item label="新密码" prop="newPassword" placeholder="请输入新密码">
                <el-input v-model="ruleForm.newPassword" type="password" show-password />
            </el-form-item>
            <el-form-item label="再次输入新密码" prop="passwordCheck" placeholder="请再次输入新密码">
                <el-input v-model="ruleForm.passwordCheck" type="password" show-password />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submit">确定</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<script setup lang="ts">
import { ChatDotRound, Setting } from '@element-plus/icons-vue';
import { onMounted, ref, reactive } from 'vue';
import { useRouter, RouterView } from 'vue-router';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import axios from '@/utils/request'
import { empAccount, msgNum } from '@/store';
import type { ImageProps } from 'element-plus'
import { getToken, removeToken } from '@/utils/auth';
import { monitorOffLine } from '@/utils/monitorOffLine';
import moment from 'moment';
const formSize = ref<ComponentSize>('default')
const accountStore = empAccount()
//获取当前员工账号
const account = ref(accountStore.$state.account)
const msgNumStore = msgNum()
//获取消息数量
const msgNumStoreData = ref(msgNumStore.$state.msgNum)
const name = ref('')
const avatarDialogVisible = ref(false)
const modifyAvatarDialogVisible = ref(false)
//获取请求头
const getTokenHeaders = reactive({
    token: getToken()
})
//只要一挂载组件就发送请求（生命周期函数）
onMounted(() => {
    getEmpInfo()
    router.push('/userMenu')
    // 监听页面关闭事件,关闭页面时发送请求
    monitorOffLine('/emp/logout', accountStore.$state.account, accountStore.$state.loginDate, accountStore.$state.onlineStartTime)
})
const getEmpInfo = async () => {
    try {
        // 发送GET请求获取员工信息
        const result = await axios.get(`/emp/${account.value}`);
        // 如果返回的状态码为1，表示成功
        if (result.data.code === 1) {
            //获取登录时间的相关信息
            const loginDate = moment().format('YYYY-MM-DD');
            const onlineStartTime = moment().format('YYYY-MM-DD HH:mm:ss');
            // 存储登录信息
            accountStore.$state.account = account.value;
            accountStore.$state.loginDate = loginDate;
            accountStore.$state.onlineStartTime = onlineStartTime;
            // 更新头像的src值
            src.value = result.data.data.image;
            name.value = result.data.data.name;
            //储存头像
            accountStore.$state.image = result.data.data.image
            //储存姓名
            accountStore.$state.name = result.data.data.name
            //储存性别
            accountStore.$state.gender = result.data.data.gender
            //储存员工id
            accountStore.$state.id = result.data.data.id
        } else if (result.data.code === 0) { }
    } catch (error) { }
};
//修改图片的方法
const modifyEmpImage = `/api/emp/upload/${account.value}`
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
    src.value = response.data
    //提示修改成功
    ElMessage.success('修改成功')
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (file) => {
    const allowedImageTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/svg+xml'];  // 定义允许的图片类型数组，可根据实际需求添加更多类型
    const isImage = allowedImageTypes.includes(file.type);
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isImage) {
        ElMessage.error("上传的文件必须是图片格式!");
    }
    if (!isLt2M) {
        ElMessage.error("上传的图片大小不能超过 2MB!");
    }
    return isImage && isLt2M;
};

const src = ref('')
const router = useRouter();
function toUserMenu() {
    router.push('/userMenu')
}
const fits = [
    'fill',
    'contain',
    'cover',
    'none',
    'scale-down',
] as ImageProps['fit'][]
const modifyDialogVisible = ref(false)
const ruleForm = reactive({
    newPassword: '',
    passwordCheck: ''
})
const modifyRules = reactive<FormRules>({
    newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, message: '密码长度必须大于六', trigger: 'blur' },
    ],
    passwordCheck: [
        { required: true, message: '请再次输入新密码', trigger: 'blur' },
        { min: 6, message: '密码长度必须大于六', trigger: 'blur' },
    ]
})

const submit = async () => {
    // 发送请求
    if (ruleForm.newPassword !== ruleForm.passwordCheck) {
        ElMessage.error('两次输入的密码不一致');
        return;
    }
    try {
        const result = await axios.put(`/emp`, {
            account: account.value,
            password: ruleForm.newPassword,
        });
        if (result.data.code === 1) {
            ElMessage.success('密码修改成功');
            // 关闭对话框
            modifyDialogVisible.value = false;
        } else {
            ElMessage.error('密码修改失败');
        }
    } catch (error) {
        ElMessage.error('修改密码时发生错误');
    }
}

function exit() {
    router.push('/userLogin')
    removeToken();
}
function toUserMessage() {
    router.push('/userHome/userChat')
}
</script>

<style>
:blank {
    background-color: azure;
}
</style>